﻿package de.gameduell.framework.facebook.app.pyramide {
	import de.gameduell.framework.facebook.app.Controller;
	import de.gameduell.framework.facebook.app.GameData;
	import de.gameduell.framework.facebook.app.PageManager;
	import de.gameduell.framework.facebook.app.popups.AlertPopup;

	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.util.Library;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;

	public class PyramidView {
		protected var controller:Controller;
		protected var _pyramid:Pyramid;
		protected var brickViews:Array;
		protected var timeline:Sprite;
		protected var pyrContainer:Sprite;
		protected var stateLayer:Sprite;
		protected var topBrickView:BrickView;
		private var firstTimeStart:Boolean;
		private var library:Library;
		private var brick_positions:Array = [];
		private var pageManager:PageManager;

		public function PyramidView(aTimeline:Sprite) {
			library = Library.getInstance();
			pageManager = PageManager.getInstance();
			// contains sprites width coordinates for the bricks
			firstTimeStart = true;
			timeline = aTimeline;
			pyrContainer = new Sprite();
			stateLayer = new Sprite();
			//			pyrContainer.y = 415;
			//			stateLayer.y = 415;
			timeline.addChild(pyrContainer);
			timeline.addChild(stateLayer);
			
			brickViews = new Array();
			controller = Controller.getInstance();
			controller.gameData.addEventListener(GameData.APP_INIT_DONE, onSetupDone);
			
			_pyramid = controller.gameData.pyramid;
			_pyramid.addEventListener(Pyramid.NEW_CONSTRUCTION, updateLayout);
			_pyramid.addEventListener(Pyramid.OUT_OF_BRICKS, onOutOfBricks);
			
			pyrContainer.cacheAsBitmap = true;
			stateLayer.cacheAsBitmap = true;
			
			var pos:Sprite = library.createSprite("brick_positions") as Sprite;
			//			stateLayer.addChild(pos);
			//			var positionCount:int = 22;
			var i:int = 0;
			while(true) {
				var sprite:Sprite = pos.getChildByName("pos_" + i) as Sprite;
				if(sprite == null) {
					break;
				}
				brick_positions[i] = sprite;
				i++;
			}
		}

		// FIXME - it's just a workaround for showing the whole pyramid
		protected function onOutOfBricks(event:Event = null):void {
			new AlertPopup("outOfBricksPopup", 0, false);
			topBrickView = BrickView(brickViews["28"]);
//			if(topBrickView != null) {
//				topBrickView.setIsOnTop(true, 6);
//			}
		}

		private function handleBorderBricks(event:Event = null):void {
			for(var i:int = 0;i < 6;i++) {
				var aRow:Array = _pyramid.getBricksByRow(i);
				var brickRow:Array = new Array();
				for each(var myBrick:Brick in aRow) {
					if(myBrick != null) {
						if(myBrick.state == Brick.STATE_COMPLETED) {
							brickRow.push(myBrick.id);
						}
					}
				}
				if(brickRow.length > 1) {
					BrickView(brickViews[brickRow[0]]).align = "left";
					if(brickRow.length > 1) {
						BrickView(brickViews[brickRow[brickRow.length - 1]]).align = "right";
						if(brickRow.length > 2) {
							BrickView(brickViews[brickRow[brickRow.length - 2]]).align = "normal";
						}
					}
				}
			}
		}

		protected function updateLayout(event:Event = null):void {
			var bricks:Array = _pyramid.getBricksByRow(0);
			var visibleWidth:int = 0;
			for(var i:int = 0;i < bricks.length;i++) {
				if(bricks[i] != null) {
					var brick:Brick = Brick(bricks[i]);
					if(BrickView(brickViews[brick.id]).sprite.visible) {
						visibleWidth += 91;
					}
				}
			}
			handleBorderBricks();
			var newX:int = int((760 - visibleWidth) / 2);
			if(newX != pyrContainer.x) {
				stateLayer.visible = false;
				//				pyrContainer.x = newX;
				checkForTopBrick();
			} else {
				checkForTopBrick();
			}
			// tracking info for media loading times ..
			if(firstTimeStart) {
				firstTimeStart = false;
				controller.stopInitTime();
			}
		}

		protected function checkForTopBrick(event:Event = null):void {
			stateLayer.x = pyrContainer.x;
			stateLayer.visible = true;
			
			var result:Array = getVisibleTopBrick();
			var topBrick:BrickView = null;
			var topRow:int = -1;
			if(result != null) {
				topBrick = BrickView(brickViews[result[0]]);
				topRow = int(result[1]);
			} 
			if(topBrick != null) {
//				topBrick.setIsOnTop(true, topRow);
//				topBrickView = topBrick;
			} else {
				if(topBrickView != null) {
//					topBrickView.setIsOnTop(false, topRow);
				}
			}
		}

		protected function getVisibleTopBrick():Array {
			for(var n:int = 0;n < _pyramid.size - 1;n++) {
				var bricks:Array = _pyramid.getBricksByRow(n);
				var bricksVisible:int = 0;
				var brickId:String = null;
				for(var i:int = 0;i < bricks.length;i++) {
					if(bricks[i] != null) {
						var brick:Brick = Brick(bricks[i]);
						if(BrickView(brickViews[brick.id]).sprite.visible) {
							bricksVisible++;
							brickId = brick.id;
						}
					}
				}
				if(bricksVisible == 1) {
					return [brickId, n];
				}
			}
			return null;
		}

		protected function onSetupDone(event:Event = null):void {
			if(_pyramid != null) {
				var i:int = 0;
				for each(var aBrick:Brick in _pyramid.bricks) {
					var position:Sprite = Sprite(brick_positions[i]);
					var aView:BrickView = new BrickView(aBrick, stateLayer, _pyramid.isForeign);
					brickViews[aBrick.id] = aView;
					pyrContainer.addChild(aView.sprite);
					var xPos:int = position.x;
					var yPos:int = position.y;
					aView.position = new Point(xPos, yPos);
					aView.addEventListener(BrickView.BRICKVIEW_CHANGED, handleBorderBricks);
					i++;
				}
			}
			updateLayout();
			
			if(_pyramid.currentBrick.id == "27") {
				onOutOfBricks();
			}
			// load icons-lib
//			pageManager.loadBricks();
		}
		
		public function update():void {
			onSetupDone();
		}
	}
}
